<template>
  <view class="page">
    <!-- 欢迎区域 -->
    <view class="welcome-section">
      <text class="welcome-title">欢迎回来</text>
      <text class="welcome-subtitle">{{ platformName || '星点互助帮' }}</text>
    </view>

    <view class="login-card">
      <!-- 微信快捷登录按钮 -->
      <button 
        class="wechat-btn" 
        open-type="getPhoneNumber"
        @getphonenumber="handleGetPhoneNumber"
      >
        <text class="wechat-icon">💬</text>
        <text class="wechat-text">手机号一键登录</text>
      </button>

      <!-- 分割线 -->
      <view class="divider">
        <view class="divider-line"></view>
        <text class="divider-text">或使用手机号登录</text>
        <view class="divider-line"></view>
      </view>

      <!-- 手机号输入 -->
      <view class="form-group">
        <text class="form-label">手机号</text>
        <view class="input-wrapper">
          <text class="input-icon">📱</text>
          <input 
            class="input-field" 
            type="number" 
            v-model="form.phone" 
            placeholder="请输入手机号"
            maxlength="11"
          />
        </view>
      </view>

      <!-- 密码输入 -->
      <view class="form-group">
        <text class="form-label">密码</text>
        <view class="input-wrapper">
          <text class="input-icon">🔒</text>
          <input 
            v-if="showPassword"
            class="input-field" 
            type="text" 
            v-model="form.password" 
            placeholder="请输入密码"
          />
          <input 
            v-else
            class="input-field" 
            type="password" 
            v-model="form.password" 
            placeholder="请输入密码"
          />
          <text class="show-password" @click="showPassword = !showPassword">
            {{ showPassword ? '👁️' : '👁️‍🗨️' }}
          </text>
        </view>
      </view>

      <!-- 登录按钮 -->
      <view class="btn-login" @click="handleLogin">
        <text class="btn-text">登录</text>
      </view>

      <!-- 还没有账号 -->
      <view class="register-section">
        <text class="register-text">还没有账号？</text>
        <text class="register-link" @click="goToRegister">立即注册</text>
      </view>

      <!-- 获取头像和昵称 -->
      <view class="wechat-info" v-if="wechatStep === 2">
        <view class="info-container">
          <view class="info-title">完善个人信息</view>
          
          <!-- 获取头像 -->
          <view class="info-item avatar-item">
            <text class="label">微信头像</text>
            <button 
              class="avatar-btn" 
              open-type="chooseAvatar"
              @chooseavatar="handleChooseAvatar"
            >
              <image :src="avatarUrl || '/static/default-avatar.png'" class="avatar-img"></image>
              <view class="avatar-overlay">
                <text class="avatar-text">{{ avatarUrl ? '更换' : '选择' }}</text>
              </view>
            </button>
          </view>
          
          <!-- 获取昵称 -->
          <view class="info-item nickname-item">
            <text class="label">微信昵称</text>
            <input 
              type="nickname" 
              v-model="nickName"
              placeholder="点击输入或获取微信昵称"
              class="nickname-input"
              @change="handleNicknameChange"
            />
          </view>
          
          <!-- 确认按钮 -->
          <button 
            class="confirm-btn"
            :disabled="!avatarUrl || !nickName"
            @tap="handleConfirmInfo"
          >
            确认并登录
          </button>
        </view>
      </view>
    </view>

    <!-- 底部隐私政策 -->
    <view class="footer-policy">
      <view class="policy-checkbox" @tap="togglePolicy">
        <view class="custom-checkbox" :class="{ 'checked': agreePolicy }">
          <text class="check-icon" v-if="agreePolicy">✓</text>
        </view>
        <view class="policy-content">
          <text class="policy-text">登录即表示同意</text>
          <text class="policy-link" @tap.stop="showUserAgreement">《用户协议》</text>
          <text class="policy-text">和</text>
          <text class="policy-link" @tap.stop="showPrivacyPolicy">《隐私政策》</text>
        </view>
      </view>
    </view>

    <!-- 协议同意弹窗 -->
    <view class="policy-modal" v-if="showPolicyModal" @tap="closePolicyModal">
      <view class="modal-content" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">温馨提示</text>
        </view>
        
        <view class="modal-body">
          <text class="modal-text">为了更好地保障您的权益，请您阅读并同意</text>
          <view class="modal-links">
            <text class="modal-link" @tap="showUserAgreement">《用户协议》</text>
            <text class="modal-text">和</text>
            <text class="modal-link" @tap="showPrivacyPolicy">《隐私政策》</text>
          </view>
        </view>
        
        <view class="modal-footer">
          <view class="modal-btn cancel-btn" @tap="closePolicyModal">
            <text class="btn-text">暂不同意</text>
          </view>
          <view class="modal-btn confirm-btn" @tap="agreePolicyAndLogin">
            <text class="btn-text">同意并继续</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  data() {
    return {
      form: {
        phone: '',
        password: ''
      },
      showPassword: false,
      agreePolicy: false,
      showPolicyModal: false,
      loading: false,
      platformName: '',
      pendingAction: null, // 记录待执行的操作
      // 微信登录相关数据
      wechatStep: 1,
      code: '',
      phoneCode: null,
      encryptedData: null,
      iv: null,
      avatarUrl: '',
      nickName: '',
      tempAvatarPath: ''
    }
  },
  methods: {
    ...mapActions('user', ['login', 'getUserInfo']),
    
    // 切换协议同意状态
    togglePolicy() {
      this.agreePolicy = !this.agreePolicy
    },
    
    // 显示用户协议
    showUserAgreement() {
      wx.openPrivacyContract({
        success: () => {
          console.log('用户打开了用户协议')
        },
        fail: () => {
          console.log('用户拒绝打开用户协议')
        }
      })
    },
    
    // 显示隐私政策
    showPrivacyPolicy() {
      wx.openPrivacyContract({
        success: () => {
          console.log('用户打开了隐私政策')
        },
        fail: () => {
          console.log('用户拒绝打开隐私政策')
        }
      })
    },
    
    // 关闭协议弹窗
    closePolicyModal() {
      this.showPolicyModal = false
      this.pendingAction = null
    },
    
    // 同意协议并继续操作
    agreePolicyAndLogin() {
      this.agreePolicy = true
      this.showPolicyModal = false
      
      // 执行之前暂存的操作
      if (this.pendingAction === 'login') {
        this.doLogin()
      } else if (this.pendingAction === 'wechat') {
        this.doWechatLogin()
      }
      
      this.pendingAction = null
    },
    
    // 检查协议并显示弹窗
    checkPolicyWithModal(action) {
      if (!this.agreePolicy) {
        this.pendingAction = action
        this.showPolicyModal = true
        return false
      }
      return true
    },
    
    async handleLogin() {
      // 检查是否同意协议
      if (!this.checkPolicyWithModal('login')) {
        return
      }
      
      // 执行登录
      await this.doLogin()
    },
    
    async doLogin() {
      // 表单验证
      if (!this.form.phone) {
        uni.showToast({ title: '请输入手机号', icon: 'none' })
        return
      }
      if (!/^1[3-9]\d{9}$/.test(this.form.phone)) {
        uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
        return
      }
      if (!this.form.password) {
        uni.showToast({ title: '请输入密码', icon: 'none' })
        return
      }
      if (this.form.password.length < 6) {
        uni.showToast({ title: '密码至少6位', icon: 'none' })
        return
      }
      
      if (this.loading) return
      this.loading = true
      
      try {
        uni.showLoading({ title: '登录中...' })
        
        await this.login({
          phone: this.form.phone,
          password: this.form.password
        })
        
        await this.getUserInfo()
        
        uni.hideLoading()
        uni.showToast({ title: '登录成功', icon: 'success' })
        
        setTimeout(() => {
          uni.switchTab({ url: '/pages/index/index' })
        }, 1500)
      } catch (error) {
        uni.hideLoading()
        
        let errorMsg = '登录失败'
        if (error.msg) {
          errorMsg = error.msg
        } else if (error.message) {
          errorMsg = error.message
        }
        
        uni.showToast({ 
          title: errorMsg, 
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.loading = false
      }
    },
    
    async handleGetPhoneNumber(e) {
      // 检查用户是否授权手机号
      if (e.detail.errMsg !== 'getPhoneNumber:ok') {
        uni.showToast({ title: '用户取消登录', icon: 'none' })
        return
      }
      
      // 保存微信返回的数据
      this.phoneCode = e.detail.code
      this.encryptedData = e.detail.encryptedData
      this.iv = e.detail.iv
      
      // 检查是否同意协议
      if (!this.checkPolicyWithModal('wechat')) {
        return
      }
      
      // 执行微信登录
      await this.doWechatLogin()
    },
    
    async doWechatLogin() {
      if (this.loading) return
      this.loading = true
      
      try {
        uni.showLoading({ title: '快捷登录中...' })
        
        // 获取登录code
        const loginRes = await uni.login()
        if (!loginRes || !loginRes[1] || !loginRes[1].code) {
          throw new Error('获取微信登录code失败')
        }
        
        this.code = loginRes[1].code
        
        const { wxLogin } = require('@/api/user')
        const checkData = {
          code: this.code,
          phoneCode: this.phoneCode,
          encryptedData: this.encryptedData,
          iv: this.iv
        }
        
        const result = await wxLogin(checkData)
        
        if (result && result.token) {
          if (result.needsInfo) {
            uni.hideLoading()
            this.wechatStep = 2
          } else {
            this.$store.commit('user/SET_TOKEN', result.token)
            await this.getUserInfo()
            
            uni.hideLoading()
            uni.showToast({ title: '登录成功', icon: 'success' })
            
            setTimeout(() => {
              uni.switchTab({ url: '/pages/index/index' })
            }, 1500)
          }
        } else {
          throw new Error('登录失败')
        }
      } catch (error) {
        uni.hideLoading()
        
        let errorMsg = '微信登录失败'
        if (error.msg) {
          errorMsg = error.msg
        } else if (error.message) {
          errorMsg = error.message
        }
        
        uni.showToast({ 
          title: errorMsg, 
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.loading = false
      }
    },
    
    handleChooseAvatar(e) {
      try {
        this.avatarUrl = e.detail.avatarUrl
        uni.showToast({
          title: '头像已选择',
          icon: 'success',
          duration: 1000
        })
      } catch (error) {
        uni.showToast({
          title: '头像选择失败',
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    handleNicknameChange(e) {
      this.nickName = e.detail.value
    },
    
    async handleConfirmInfo() {
      if (!this.avatarUrl || !this.nickName) {
        uni.showToast({
          title: '请完善个人信息',
          icon: 'none'
        })
        return
      }
      
      await this.completeWxLogin()
    },
    
    async completeWxLogin() {
      try {
        uni.showLoading({ title: '登录中...' })
        
        // 重新获取新的 code（因为之前的 code 已经在第一次调用时使用了）
        const loginRes = await uni.login()
        if (!loginRes || !loginRes[1] || !loginRes[1].code) {
          throw new Error('获取微信登录code失败')
        }
        
        const { wxLogin } = require('@/api/user')
        const loginData = {
          code: loginRes[1].code, // 使用新获取的 code
          phoneCode: this.phoneCode,
          encryptedData: this.encryptedData,
          iv: this.iv,
          nickName: this.nickName || '微信用户',
          avatarUrl: this.avatarUrl || '',
          gender: 0
        }
        
        const result = await wxLogin(loginData)
        
        if (result && result.token) {
          this.$store.commit('user/SET_TOKEN', result.token)
          await this.getUserInfo()
          
          uni.hideLoading()
          uni.showToast({ title: '登录成功', icon: 'success' })
          
          setTimeout(() => {
            uni.switchTab({ url: '/pages/index/index' })
          }, 1500)
        } else {
          throw new Error('登录失败')
        }
      } catch (error) {
        uni.hideLoading()
        
        let errorMsg = '登录失败'
        if (error.msg) {
          errorMsg = error.msg
        } else if (error.message) {
          errorMsg = error.message
        }
        
        // 如果是 code 被使用的错误，提示更友好的信息
        if (errorMsg.includes('code been used') || errorMsg.includes('code been used')) {
          errorMsg = '登录码已失效，请重新尝试'
        }
        
        uni.showToast({ 
          title: errorMsg, 
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.loading = false
      }
    },
    
    goToRegister() {
      uni.navigateTo({ url: '/pages/user/register' })
    }
  },
  
  onLoad() {
    this.platformName = this.$store.state.platformName || '星点互助帮'
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: linear-gradient(
    to bottom right,
    #f0fdf4,
    #eff6ff,
    #faf5ff
  );
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 60rpx 30rpx 40rpx;
  position: relative;
  overflow: hidden;
  padding-top: 100rpx;
  
  &::before {
    content: '';
    position: absolute;
    top: 80rpx;
    left: 40rpx;
    width: 160rpx;
    height: 160rpx;
    background-color: #bbf7d0;
    border-radius: 50%;
    opacity: 0.2;
    filter: blur(128rpx);
    z-index: 0;
  }
  
  &::after {
    content: '';
    position: absolute;
    bottom: 80rpx;
    right: 40rpx;
    width: 200rpx;
    height: 200rpx;
    background-color: #bfdbfe;
    border-radius: 50%;
    opacity: 0.2;
    filter: blur(128rpx);
    z-index: 0;
  }
}

.welcome-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 60rpx;
  position: relative;
  z-index: 1;
  
  .welcome-title {
    font-size: 48rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 12rpx;
  }
  
  .welcome-subtitle {
    font-size: 28rpx;
    color: #999;
  }
}

.login-card {
  width: 100%;
  max-width: 560rpx;
  background: #fff;
  border-radius: 32rpx;
  padding: 48rpx 40rpx;
  box-shadow: 0 10rpx 40rpx rgba(0, 0, 0, 0.08);
  position: relative;
  z-index: 1;
}

.wechat-btn {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  background: #07c160;
  border-radius: 16rpx;
  padding: 28rpx;
  border: none;
  margin-bottom: 32rpx;
  
  .wechat-icon {
    font-size: 36rpx;
  }
  
  .wechat-text {
    font-size: 30rpx;
    color: #fff;
    font-weight: bold;
  }
}

.divider {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 40rpx;
  
  .divider-line {
    flex: 1;
    height: 1rpx;
    background: #e0e0e0;
  }
  
  .divider-text {
    font-size: 26rpx;
    color: #999;
  }
}

.form-group {
  margin-bottom: 28rpx;
  
  .form-label {
    display: block;
    font-size: 26rpx;
    color: #333;
    margin-bottom: 12rpx;
    font-weight: 500;
  }
}

.input-wrapper {
  display: flex;
  align-items: center;
  background: #f8f8f8;
  border: 2rpx solid #e8e8e8;
  border-radius: 14rpx;
  padding: 18rpx 20rpx;
  gap: 12rpx;
  transition: all 0.3s ease;
  
  &:focus-within {
    border-color: #07c160;
    background: #fff;
  }
  
  .input-icon {
    font-size: 32rpx;
    flex-shrink: 0;
  }
  
  .input-field {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    background: transparent;
    
    &::placeholder {
      color: #ccc;
    }
  }
  
  .show-password {
    font-size: 32rpx;
    cursor: pointer;
    flex-shrink: 0;
  }
}

.btn-login {
  width: 85%;
  background: linear-gradient(90deg, #07c160 0%, #0084ff 100%);
  border-radius: 16rpx;
  padding: 28rpx 24rpx;
  text-align: center;
  margin-bottom: 28rpx;
  box-shadow: 0 4rpx 16rpx rgba(7, 193, 96, 0.3);
  
  .btn-text {
    font-size: 32rpx;
    font-weight: bold;
    color: #fff;
  }
}

.register-section {
  text-align: center;
  
  .register-text {
    font-size: 26rpx;
    color: #666;
  }
  
  .register-link {
    font-size: 26rpx;
    color: #07c160;
    font-weight: bold;
    margin-left: 8rpx;
  }
}

.wechat-info {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 32rpx;
  z-index: 1000;
  
  .info-container {
    background: white;
    border-radius: 24rpx;
    padding: 48rpx 40rpx;
    width: 100%;
    max-width: 600rpx;
    box-shadow: 0 10rpx 40rpx rgba(0, 0, 0, 0.1);
  }
  
  .info-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 48rpx;
    text-align: center;
  }
  
  .info-item {
    margin-bottom: 40rpx;
    
    .label {
      display: block;
      font-size: 26rpx;
      color: #666666;
      margin-bottom: 16rpx;
      font-weight: 500;
    }
  }
  
  .avatar-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 48rpx;
  }
  
  .avatar-btn {
    position: relative;
    width: 140rpx;
    height: 140rpx;
    border-radius: 16rpx;
    overflow: hidden;
    border: none;
    padding: 0;
    background: transparent;
    
    .avatar-img {
      width: 100%;
      height: 100%;
      border-radius: 16rpx;
      object-fit: cover;
    }
    
    .avatar-overlay {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.4);
      padding: 8rpx 0;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .avatar-text {
        color: white;
        font-size: 24rpx;
        font-weight: bold;
      }
    }
  }
  
  .nickname-item {
    .nickname-input {
      width: 100%;
      padding: 18rpx 20rpx;
      border: 2rpx solid #e0e0e0;
      border-radius: 12rpx;
      font-size: 28rpx;
      color: #333333;
      background: #f9f9f9;
      transition: all 0.3s ease;
      
      &:focus {
        border-color: #07c160;
        background: white;
      }
      
      &::placeholder {
        color: #999999;
      }
    }
  }
  
  .confirm-btn {
    width: 100%;
    background: linear-gradient(90deg, #07c160 0%, #05a84d 100%);
    color: white;
    border-radius: 12rpx;
    padding: 24rpx;
    font-size: 32rpx;
    font-weight: bold;
    margin-top: 48rpx;
    border: none;
    box-shadow: 0 4rpx 16rpx rgba(7, 193, 96, 0.3);
    transition: all 0.3s ease;
    
    &:active:not(:disabled) {
      transform: scale(0.98);
      box-shadow: 0 2rpx 8rpx rgba(7, 193, 96, 0.2);
    }
    
    &:disabled {
      background: #cccccc;
      box-shadow: none;
      opacity: 0.6;
    }
  }
}

.footer-policy {
  margin-top: 32rpx;
  position: relative;
  z-index: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  
  .policy-checkbox {
    display: flex;
    align-items: flex-start;
    gap: 12rpx;
    cursor: pointer;
  }
  
  .custom-checkbox {
    width: 32rpx;
    height: 32rpx;
    border: 2rpx solid #d0d0d0;
    border-radius: 6rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    transition: all 0.3s ease;
    margin-top: 2rpx;
    
    &.checked {
      background: #07c160;
      border-color: #07c160;
    }
    
    .check-icon {
      color: #fff;
      font-size: 24rpx;
      font-weight: bold;
    }
  }
  
  .policy-content {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    font-size: 24rpx;
    line-height: 1.6;
  }
  
  .policy-text {
    color: #999;
  }
  
  .policy-link {
    color: #07c160;
    font-weight: 500;
    margin: 0 4rpx;
  }
}

/* 协议弹窗 */
.policy-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  padding: 40rpx;
  
  .modal-content {
    background: #fff;
    border-radius: 24rpx;
    width: 100%;
    max-width: 560rpx;
    overflow: hidden;
  }
  
  .modal-header {
    padding: 40rpx 32rpx 24rpx;
    text-align: center;
    
    .modal-title {
      font-size: 34rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .modal-body {
    padding: 0 32rpx 32rpx;
    
    .modal-text {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
    }
    
    .modal-links {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      margin-top: 8rpx;
      
      .modal-link {
        font-size: 28rpx;
        color: #07c160;
        font-weight: 500;
        margin: 0 4rpx;
      }
    }
  }
  
  .modal-footer {
    display: flex;
    border-top: 1rpx solid #f0f0f0;
    
    .modal-btn {
      flex: 1;
      padding: 32rpx;
      text-align: center;
      
      .btn-text {
        font-size: 30rpx;
        font-weight: 500;
      }
      
      &.cancel-btn {
        color: #999;
        border-right: 1rpx solid #f0f0f0;
      }
      
      &.confirm-btn {
        color: #07c160;
        font-weight: bold;
      }
    }
  }
}
</style>